/// <remarks>
/// MainForm Class
/// This class contain the main panel and the logger textbox.
/// 
/// Author: Georges Marceau, Matricis Informatique Inc.
/// Co-Author: Louis-Philippe Lebouthillier.
/// </remarks>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using VcLib;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.VersionControl.Common;

namespace VcGUI
{
    public partial class MainForm : Form
    {
        private Logger logger = null;
        private VcLib.TFSFacade VcUtil = VcLib.TFSFacade.Instance;
        private VcLib.Config config = VcLib.Config.Instance;

        public MainForm()
        {
            try
            {
                InitializeComponent();

                this.logger = Logger.Instance;
                this.logger.TextBoxLogger = this.txtOutput;

                logger.DebugInfo("Team System Version Control Client");
                logger.DebugInfo("Thanks to Matricis Informatique to make this project possible");
                logger.DebugInfo("Visit us @ http://www.matricis.com/ & codeplex @ http://www.codeplex.com/TSVcClient");

                this.config.ServerName = ConfigurationManager.AppSettings.Get("servername");
                this.txtServerName.Text = this.config.ServerName;
                this.AcceptButton = this.btnRefresh;
                
                SetListView();
            }
            catch(Exception ex)
            {
                this.logger.Error(ex.Message);
            }
        }

        private void SetListView()
        {
            ColumnHeader colHead;

            colHead = new ColumnHeader();
            colHead.Text = "Projects";
            colHead.Width = 170;           
            this.lstProjects.Columns.Add(colHead);

            colHead = new ColumnHeader();
            colHead.Text = "Working Folder";
            colHead.Width = 500;            
            this.lstProjects.Columns.Add(colHead);     
        }

        // Call API to list all projects on the selected server.
        public void PopulateProjectsList()
        {
            try
            {
                string addressBegin;
                addressBegin = txtServerName.Text.Remove(4);
                
                if (addressBegin.ToLower() != "http")
                    this.logger.Error("Server address MUST begin with http or https");
                else
                {
                    ListViewItem lvi;
                    TeamProject[] tps = VcUtil.GetTeamProjects();
                    IDictionary<string, string> dic = new Dictionary<string, string>();
                    dic = VcUtil.GetActiveWorkingFolderList();
                    this.lstProjects.Items.Clear();
                    this.lstProjects.BeginUpdate();

                    foreach (KeyValuePair<string, string> pair in dic)
                    {
                        lvi = new ListViewItem();
                        ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
                        lvi.Text = pair.Key;
                        lvsi.Text = pair.Value;
                        lvi.SubItems.Add(lvsi);
                        this.lstProjects.Items.Add(lvi);
                    }

                    this.lstProjects.EndUpdate();
                    this.lstProjects.Refresh();
                    this.lstProjects.View = View.Details;
                    this.logger.Info("List Refreshed");
                }
            }
            catch(ArgumentNullException)
            {
                this.logger.Error("Enter a server name");
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.Message);
            }
        }

        // When the selected server change, update the config file.
        private void UpdateConfig()
        {
            string configPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\VcGUI.exe";
            System.Configuration.Configuration configMan = ConfigurationManager.OpenExeConfiguration(configPath);
            configMan.AppSettings.Settings.Remove("servername");
            configMan.AppSettings.Settings.Add("servername", txtServerName.Text);
            configMan.Save(ConfigurationSaveMode.Modified);

            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
            config.ServerName = txtServerName.Text;
        }

        // Open AddFiles Form
        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            if (!IsProjectSelected())
                return;

            string localPath = lstProjects.SelectedItems[0].SubItems[1].Text;
            Form addFiles = new AddFilesFrm(txtProject.Text, localPath);
            addFiles.MdiParent = this;
            this.splitContainer1.Panel1.Controls.Add(addFiles);
            addFiles.Dock = DockStyle.Fill;
            addFiles.Show();
        }

        // Open CheckIn Form
        private void btnCheckIn_Click(object sender, EventArgs e)
        {
            if (!IsProjectSelected())
                return;

            string localPath = lstProjects.SelectedItems[0].SubItems[1].Text;
            Form checkIn = new CheckInFrm(this.txtProject.Text, localPath);
            checkIn.MdiParent = this;
            this.splitContainer1.Panel1.Controls.Add(checkIn);
            checkIn.Dock = DockStyle.Fill;
            checkIn.Show();
        }

        // Open GetLatest Form
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!IsProjectSelected())
                return;

            string localPath = lstProjects.SelectedItems[0].SubItems[1].Text;
            Form GetLatest = new GetLatestFrm(txtProject.Text, localPath);
            GetLatest.MdiParent = this;
            this.splitContainer1.Panel1.Controls.Add(GetLatest);
            GetLatest.Dock = DockStyle.Fill;
            GetLatest.Show();
        }

        // Check if a project is selected before opening a form
        private bool IsProjectSelected()
        {
            if (lstProjects.SelectedItems.Count > 0)
                return true;
            else
            {
                this.logger.Error("No project selected");
                return false;
            }
        }

        private void btnSetWorkingFolder_Click(object sender, EventArgs e)
        {
            try
            {
                string project = "";
                string localPath = "";
                if (IsProjectSelected())
                {
                    localPath = lstProjects.SelectedItems[0].SubItems[1].Text;
                    project = txtProject.Text;
                }

                WorkSpaceFrm wsFrm = new WorkSpaceFrm(this.txtServerName.Text, this.txtProject.Text);
                wsFrm.MdiParent = this;
                this.splitContainer1.Panel1.Controls.Add(wsFrm);
                wsFrm.Dock = DockStyle.Fill;
                wsFrm.Show();
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.Message);
            }
        }

        private void lstProjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstProjects.SelectedItems.Count > 0)
                this.txtProject.Text = lstProjects.SelectedItems[0].SubItems[0].Text;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.logger.ServerInfo("Connecting to the server...");
                this.btnRefresh.Enabled = false;
                UpdateConfig();
                VcUtil.Connect();
                PopulateProjectsList();
                txtServerName.Focus();
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            finally
            {
                this.btnRefresh.Enabled = true;
            }
        }

        private void createWorkingFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutFrm about = new AboutFrm();
            about.Show();
        }

        public Panel GetMainPanel
        {
           get
           {
               return this.splitContainer1.Panel1;
           }
        }
    }
}